<script lang="ts">
import { defineComponent, ref, onMounted } from "vue";
import { useRouter } from "vue-router";

interface HotWordItem {
  color: string;
  query: string;
  acm: string;
  frontword: string;
}

interface HotWordButton {
  text: string;
  color: string;
}

export default defineComponent({
  setup() {
    const router = useRouter();
    const searchInput = ref("");
    const hotWordButtons = ref<HotWordButton[]>([]);
    const historySearches = ref<string[]>([]);

    const fetchHotWords = async () => {
      try {
        const response = await fetch("https://apis.netstart.cn/mogujie/hotSearch.json");
        const data = await response.json();
        const frontWords = (data.data.hotWord.data as HotWordItem[]).map((item) => item.frontword);
        const buttons = frontWords.map((word) => ({
          text: word,
          color: (data.data.hotWord.data.find((i) => i.frontword === word) as HotWordItem).color || "#333"
        }));
        hotWordButtons.value = buttons;
      } catch (error) {
        console.error("获取热门搜索词出现错误：", error);
      }
    };

    const goBack = () => {
      router.back();
    };

    const doSearch = () => {
      const searchTerm = searchInput.value;
      if (searchTerm) {
        const existingIndex = historySearches.value.indexOf(searchTerm);
        if (existingIndex > -1) {
          historySearches.value.splice(existingIndex, 1);
        }
        historySearches.value.unshift(searchTerm);
        localStorage.setItem('searchHistory', JSON.stringify(historySearches.value));
      }
      router.push({
        name: "SearchResult",
        query: {
          q: searchInput.value
        }
      });
    };

    const doSearchWithHistory = (searchTerm: string) => {
      router.push({
        name: "SearchResult",
        query: {
          q: searchTerm
        }
      });
    };

    const clearHistory = () => {
      historySearches.value = [];
      localStorage.removeItem('searchHistory');
    };

    const doSearchWithHotWord = (hotWord: string) => {
      // 点击热门搜索按钮时，先将对应热门词添加到历史搜索记录
      const existingIndex = historySearches.value.indexOf(hotWord);
      if (existingIndex > -1) {
        historySearches.value.splice(existingIndex, 1);
      }
      historySearches.value.unshift(hotWord);
      localStorage.setItem('searchHistory', JSON.stringify(historySearches.value));

      router.push({
        name: "SearchResult",
        query: {
          q: hotWord
        }
      });
    };

    onMounted(() => {
      fetchHotWords();
      const storedHistory = localStorage.getItem('searchHistory');
      if (storedHistory) {
        historySearches.value = JSON.parse(storedHistory);
      }
    });

    return {
      searchInput,
      hotWordButtons,
      doSearch,
      goBack,
      historySearches,
      doSearchWithHistory,
      clearHistory,
      doSearchWithHotWord
    };
  },
});
</script>
<template>
  <div class="Search">
    <div class="search-header">
      <div class="sons">
        <img src="../../public/images/返回.png" alt="返回" @click="goBack" />
        <input type="text" placeholder="搜索" v-model="searchInput" class="sosk" @keyup.enter="doSearch"/>
        <button @click="doSearch">搜索</button>
      </div>
    </div>
    <div class="history-search-container" v-if="historySearches.length > 0">
      <img src="../../public/images/放大镜.png" alt="" class="fdj">
      <span>历史搜索</span>
       <img src="../../public/images/垃圾桶.png" alt="" class="clear-history" @click="clearHistory">
      <div class="history-search-list">
        <div v-for="(search, index) in historySearches" :key="index" class="history-search-item"
          @click="doSearchWithHistory(search)">
          <button>
            {{ search }}
          </button>
        </div>
      </div>
    </div>
    <div class="xian"></div>
    <div class="button-container">
      <span><img src="../../public/images/收藏.png" alt="" class="like">热门搜索</span>
      <button v-for="(button, index) in hotWordButtons" :key="index" class="hot-word-button"
        :style="{ color: button.color }" @click="doSearchWithHotWord(button.text)">
        {{ button.text }}
      </button>
    </div>

  </div>
</template>

<style lang="less">
.vue-devtools__panel[data-v-e9063f7b] {
  display: none;
}

.search-header {
  .sons {
    width: 100%;
    margin-top: 5rem;
    height: 42rem;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    border-bottom: 1px solid #eee;

    img {
      width: 23rem;
      height: 23rem;
      cursor: pointer;
    }

    button {
      background: none;
      border: none;
      font-size: 14rem;
      color: #666;
    }
  }
}
.xian{
  width: 100%;
  height: 1px;
  background-color: #eee;
  margin-top: 10rem;
}
.sosk {
  border: 1px solid #aaa;
  padding: 1rem 3rem;
  width: 70%;
  height: 24rem;
  box-shadow: none;
  color: #000;
  font-size: 14rem;
  border-radius: 5rem;
  padding: 0rem 12rem;
}

// 点击后变成红色
.sosk:focus {
  border: 1px solid red;
  outline: none;
}

.button-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  gap: 5rem;
  padding: 5rem;
  margin-left: 10rem;
}

.button-container span {
  font-size: 13rem;
  margin-left: 13rem;
  margin-bottom: 10rem;
  margin-top: 10rem;
  color: #999;
  width: 100%;
}



.button-container button,
.hot-word-button,
.history-search-item button {
  border-radius: 5rem;
  padding: 2rem 10rem;
  font-size: 14rem;
  color: #666;
  background: none;
  border: 1px solid #99999931;
  margin: 2rem 5rem;
}

.like {
  width: 15rem;
  height: 15rem;
  margin-left: -18rem;
  position: absolute;
}

.history-search-container {
  margin-top: 20rem;
  margin-left: 10rem;

}

.history-search-container span {
  font-size: 13rem;
  margin-bottom: 10rem;
  color: #999;
  display: block;
  margin-left: 15rem;

}

.history-search-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  
  gap: 5rem;
}

.history-search-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13rem;
  color: #666;
}

.clear-history{
  width: 23rem;
  height: 23rem;
  float: right;
  margin-right: 10rem;
  margin-top: -35rem;
}

.fdj{
  width: 17rem;
  height: 17rem;
  margin-left: -2rem;
  position: absolute;
}
</style>
